<script setup>
import {getProjectlists, removeProject, jishugroup, getProjectTypeEnum, transferProjectType} from "@/api/project.js";
import {listsnopage, searchxiangmu} from "@/api/service.js";
import {computed, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import AddVue from "./add/index";
import {delay} from "@/utils";
import {STATUS_ENUM, STATUS_DESIGN, STATUS_TEST} from './status'
import {toast} from "@/hook/toast";
import AllotVue from '@/views/project-list/allot'
import confirm from "@/libs/confirm";
import CustomVue from "./custom/index"
import {EditPen} from "@element-plus/icons-vue";


const router = useRouter();
const projectlist = ref([]);
const formRef = ref(null)
const addRef = ref(null)
const loading = ref(false)
const showAllot = ref(false)
const showCustom = ref(false)
const customRef = ref(null)
const prodTypeEnum = ref([])

async function initProdTypeEnum() {
  const resp = await getProjectTypeEnum()
  if (!resp.data) resp.data = []
  prodTypeEnum.value = resp.data.map(item => {
    const {id: value, name: label} = item
    return {label, value}
  })
}

initProdTypeEnum()

const allotRef = ref(null)
// 查询项目公司
const companySearch = ref(null)
// 业务公司id
const yewu_company = ref(null)

// 是否屏蔽
const formData = ref({
  name: '',
  ui_status: '',
  status: '',
  yanshou_status: '',
  yewu_company: '',
  is_pingbi_wancheng: '屏蔽',
  jishu_group_id: '',
  xiangmutype_id: '',
})
const paginationData = ref({
  total: 0,
  pageSize: 15,
  page: 1,
})


function searchHandle() {
  formRef.value.validate(() => {
    paginationData.value.page = 1
    projectlist.value = []
    initData()
  })
}

const statusEnum = computed(() => STATUS_ENUM)
const statusDesign = computed(() => STATUS_DESIGN)
const statusTest = computed(() => STATUS_TEST)

function addHandle() {
  visible.value = true
}

// 项目小组筛选
const groupData = ref([]);

async function initData() {
  loading.value = true
  const {page} = paginationData.value
  const {
    name, ui_status, status, yanshou_status, yewu_company, xiangmutype_id,
    is_pingbi_wancheng, jishu_group_id,
  } = formData.value
  const payload = {page, is_pingbi_wancheng: is_pingbi_wancheng === '屏蔽' ? 1 : 0, xiangmutype_id}
  if (!!name) {
    payload.keyword = name
  }
  if (ui_status !== '') {
    payload.ui_status = ui_status
  }
  if (status !== '') {
    payload.status = status
  }
  if (yanshou_status !== '') {
    payload.yanshou_status = yanshou_status
  }
  if (yewu_company !== '') {
    payload.yewu_company = yewu_company
  }
  if (jishu_group_id !== '') {
    payload.jishu_group_id = jishu_group_id
  }
  const resp = await getProjectlists(payload).catch(() => {
    loading.value = false
  });
  // const resD = await jishugroup(payload).catch(() => {

  // })
  // const group = [
  //   {
  //     id: '',
  //     name: '全部'
  //   }
  // ]

  // groupData.value = [...group, ...resD.data].map((item, index) => ({
  //   name: item.name,
  //   id: item.id
  // }))


  const {code, data} = resp;
  const {total, data: list} = data
  paginationData.value.total = total
  if (code !== 1) return loading.value = false;
  if (!!list && list.length) {
    const statusEnum = {
      '1': '',
      '2': 'success',
      '3': 'warning',
      '4': 'danger',
      '7': 'danger',
    }
    const tableColStatus = {
      '1': 'info-row',
      '2': 'success-row',
      '3': 'info-row',
      '4': 'danger-row',
      '7': 'danger-row',
      '6': 'primary-row'
    }
    await delay(300)
    projectlist.value = data.data.map(item => {
      const {status, ui_status, yanshou_status} = item
      item.tagType = statusEnum[status]
      item.tagType2 = statusEnum[ui_status]
      item.tagType3 = statusEnum[yanshou_status]
      item.className = tableColStatus[status]
      item.showPopover = false
      item.changeValue = item.xiangmutype_id
      return item
    })
  }
  loading.value = false
}

const company = ref([])

// 获取公司列表
async function getCommon() {
  const resp = await listsnopage()
  const {code, data, msg} = resp
  if (code !== 1) return
  if (!!data && data.length) {
    company.value = data.map(item => {
      const {id, name} = item
      return {value: id, label: name}
    })
  }
}

// 完成与否

const complete = ref([{
  value: 1,
  label: '屏蔽'
}, {
  value: 0,
  label: '不屏蔽'
}])

// function complete(){

// }


// 选择公司 获取id进行查询
function companySear(e) {
  formData.value.yewu_company = e
}

function addSuccess() {
  resetForm()
}

function resetForm() {
  console.log('重置一下');
  formRef.value.resetFields()
  paginationData.value.page = 1
  formData.value.status = ''
  formData.value.ui_status = ''
  formData.value.yanshou_status = ''
  // formData.value.jishu_group_id = ''
  yewu_company.value = ''
  companySearch.value = ''
  formData.value.is_pingbi_wancheng = '屏蔽'
  formData.value.xiangmutype_id = ''
  projectlist.value = []
  initData()
}

function pageChange(val) {
  paginationData.value.page = val
  initData()
}


const tableHeight = ref(500)
const contentRef = ref(null)

function initHeight() {
  const element = contentRef.value
  if (!element) return
  const {height} = element.getBoundingClientRect()
  tableHeight.value = height
}


const tableRowClassName = ({row}) => {
  return row.className
}
const visible = ref(false)


async function confirmDelete(xiangmu_id) {
  const resp = await removeProject({xiangmu_id})
  const {code, msg} = resp
  const codeEnum = {
    0: 'error',
    1: 'success',
  }
  toast({title: msg, type: codeEnum[code]})
  if (code !== 1) return
  await initData()
}

function editProject(row) {
  addRef.value?.editHandle(row)
}

function allotHandle(row) {
  showAllot.value = true
  allotRef.value?.initData(row.id)
}

// 添加客户
function addCustom(row) {
  const {id} = row
  customRef.value?.editHandle(id)
}

function deleteHandle({name, id}) {
  confirm({
    message: `您确定要删除 ${name} ？`,
    title: '温馨提示!',
    confirmBtnText: '删除',
    cancelBtnText: '取消',
  }).then(() => confirmDelete(id)).catch(() => {
  })
}

function detailHandle({id}) {
  router.push({
    name: 'business-detail',
    query: {id},
  })
}

async function radioChange(e) {
  console.log('选择小组', e, formData.value.jishu_group_id)
  await initData()
}

function changeProdType(id, row) {
  console.log(id, row)
  // row.showPopover = false
}

async function confirmChangeType(row) {
  console.log(row, 'row')
  const {xiangmutype_id, id, changeValue} = row
  if (xiangmutype_id === changeValue) return row.showPopover = false

  const resp = await transferProjectType({
    xiangmu_id: id,
    xiangmutype_id: changeValue,
  })
  const {code} = resp
  if (code !== 1) return
  // row.xiangmutype_id = changeValue
  row.showPopover = false
  // console.log(resp, 'resp')
  initData()
}

function onHide(ev) {
  console.log(ev, 'ev')

}

function openPopover(row) {
  row.showPopover = true
}

onMounted(() => {
  initHeight()
  initData();
  getCommon()

});
</script>
<template>
  <div class="content relative flex column ">
    <!-- <div style="margin-bottom: 12px;">
      <el-radio-group fill="#42B983" v-model="formData.jishu_group_id" @change="radioChange">
        <el-radio-button :label="item.id" v-for="(item, index) in groupData">{{ item.name
        }}</el-radio-button>
      </el-radio-group>
    </div> -->
    <el-row class="top_header" justify="space-between">
      <el-form inline ref="formRef" hide-required-asterisk :model="formData">
        <el-form-item label="名称:" prop="name">
          <el-input placeholder="请输入项目名称" @keyup.enter="searchHandle" v-model="formData.name"/>
        </el-form-item>
        <el-form-item label="业务公司">
          <el-select v-model="companySearch" @change="companySear">
            <el-option v-for="(item, index) in company" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设计状态">
          <el-select style="width: 120px;" v-model="formData.ui_status">
            <el-option v-for="(item, index) in statusDesign " :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开发状态">
          <el-select style="width: 120px;" v-model="formData.status">
            <el-option v-for="(item, index) in statusEnum" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="验收状态">
          <el-select style="width: 120px;" v-model="formData.yanshou_status">
            <el-option v-for="(item, index) in statusTest" :key="index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目类型">
          <el-select v-model="formData.xiangmutype_id" style="width: 150px">
            <el-option v-for="(item,index) in prodTypeEnum"
                       :key="index"
                       :label="item.label"
                       :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="屏蔽已验收项目">
          <el-radio-group v-model="formData.is_pingbi_wancheng">
            <el-radio-button v-for="(item, index) in complete"
                             :key="index"
                             :label="item.label"
            />
          </el-radio-group>

        </el-form-item>

        <el-form-item>
          <el-space>
            <el-button @click="searchHandle" type="primary" icon="Search">搜索</el-button>
            <el-button type="danger" plain @click="resetForm">重置</el-button>
            <el-button type="success" @click="addHandle">添加项目</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-row>
    <div class="relative w-100 flex-1">
      <div class="absolute inset " ref="contentRef">
        <el-table border v-loading="loading" :data="projectlist" fit style="width: 100%" :height="tableHeight"
                  :row-class-name="tableRowClassName">
          <el-table-column fixed="left" prop="name" label="项目名称" width="180">
            <template #default="{ row }">
              <div @click="detailHandle(row)">{{ row.name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="yewu_company_name" label="业务公司"/>

          <el-table-column prop="ui_status_text" label="设计状态" width="90">
            <template #default="{ row }">
              <el-tag :type="row.tagType2">{{ row.ui_status_text }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status_text" label="开发状态" width="90">
            <template #default="{ row }">
              <el-tag :type="row.tagType">{{ row.status_text }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="yanshou_status_text" label="验收状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.tagType3">{{ row.yanshou_status_text }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="项目类型" width="130">
            <template #default="{row}">
              <div class="prod-type-wrap">
                <span class="type-name">{{ row.xiangmutype_text }}</span>
                <el-popover
                    placement="bottom"
                    trigger="click"
                    popper-style="width:fit-content;"
                    :visible="row.showPopover"
                >
                  <template #default>
                    <div class="type-popover-wrap">
                      <el-select size="default"
                                 v-model="row.changeValue"
                                 style="width: 140px"
                                 @change="changeProdType($event,row)"
                      >
                        <el-option v-for="(item,index) in prodTypeEnum"
                                   :key="index"
                                   :label="item.label"
                                   :value="item.value"/>
                      </el-select>
                      <el-space>
                        <el-button link @click="row.showPopover = false">取消</el-button>
                        <el-button type="primary" @click="confirmChangeType(row)">确定</el-button>
                      </el-space>
                    </div>
                  </template>
                  <template #reference>
                    <el-icon class="edit-pen" :size="16" color="rgb(128, 142, 255)" @click="openPopover(row)">
                      <EditPen/>
                    </el-icon>
                  </template>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="项目总金额" width="110" prop="xiangmu_price"/>
          <el-table-column prop="yewu_name" label="业务员"/>
          <el-table-column prop="qiandan_date" label="签单日期"/>
          <el-table-column prop="gongqi" width="60" label="合同工期"/>
          <el-table-column prop="daoqi_date" width="110" label="合同到期"/>
          <el-table-column prop="qianduan_name" label="前端"/>
          <el-table-column prop="chanpin_name" label="产品"/>
          <el-table-column prop="houduan_name" label="后端"/>
          <el-table-column prop="ui_name" label="UI"/>
          <el-table-column prop="content" :show-overflow-tooltip="true" label="备注"/>
          <el-table-column prop="jishu_yaoqiu_content" :show-overflow-tooltip="true" label="技术备注">
          </el-table-column>
          <el-table-column label="操作" width="170" align="center" fixed="right">
            <template #default="{ row }">
              <el-space>
                <el-button type="primary" plain size="small" @click="detailHandle(row)">详情</el-button>
                <el-button type="success" plain size="small" @click="addCustom(row)">绑定客户</el-button>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="page-footer">
      <el-pagination layout="prev, pager, next" :total="paginationData.total" :page-size="paginationData.pageSize"
                     :current_page="paginationData.page" @current-change="pageChange"/>
    </div>
    <div class="absolute">
      <add-vue ref="addRef" v-model="visible" @add-success="addSuccess"/>
      <!-- <allot-vue ref="allotRef" v-model="showAllot" @add-success="addSuccess" /> -->
      <custom-vue ref="customRef" v-model="showCustom" @add-success="addSuccess"></custom-vue>
    </div>
  </div>
</template>
<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .primary-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);

}

.el-table .info-row {
  --el-table-tr-bg-color: var(--el-color-info-light-9);

}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .danger-row {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);

}
</style>
<style scoped lang="scss">
.type-popover-wrap {
  display: flex;
  align-items: center;
  gap: 12px;
}

.prod-type-wrap {
  display: flex;
  align-items: center;
  line-height: 1;


  .type-name {
    margin-right: 6px;
  }

  .edit-pen {
    transition: opacity .1s ease;
    cursor: pointer;

    &:hover {
      opacity: .8;
    }
  }
}

.content {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 0 12px rgba(0, 0, 0, 0.12);
  padding: 16px 16px 0;

  .page-footer {
    padding: 16px;
    display: flex;
    justify-content: flex-end;
  }
}

.top_header {
  margin-bottom: 16px;
}

.page {
  float: right;
  margin-top: 30px;
}
</style>
